import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux'
import {API_URL,PORTRAIT,fetchPatient,fetchUserImage,updateImage,changePage ,mPacs,removeImage,fetchPortrait} from '../../store/actions';
import {message,Card, Col, Row,Button,Tag,Modal,Form,Input} from 'antd';
import _ from 'lodash';
const FormItem = Form.Item;

require('../../../css/label-list.css');

class _SpecialistDetail extends React.Component{
    constructor(props){
        super(props);
        this.state= {
            image:{},
            patient:{},
            modal:{
                title:'',
                text:'',
                visible:false
            },
            modalDel:{
                title:'',
                text:'',
                visible:false
            },
            user:this.props.user
        };
        this.handleCancel = this.handleCancel.bind(this);
        this.handleOk = this.handleOk.bind(this);
        this.handleReject = this.handleReject.bind(this);
        this.deleteImage = this.deleteImage.bind(this);
        this.handleOkDel = this.handleOkDel.bind(this);
        this.handleCancelDel = this.handleCancelDel.bind(this);
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    changePage(){
        this.props.dispatch(changePage('specialist-detail'));
    }
    handleOkDel(){
        const _this = this,
            studyId = _this.state.image.id;
        _this.setState({
            modalDel: {
                confirmLoading: true,
                visible:true,
                text:'您确认要删除这个影像吗？',
                title:'删除影像'
            }
        },function(){
            _this.props.dispatch(removeImage(studyId,function(){
                message.success('删除影像成功',1,function(){
                    _this.setState({
                        modalDel: {
                            confirmLoading: false,
                            visible:false,
                            text:'',
                            title:''
                        }
                    },function(){
                        _this.context.router.push('/images')
                    })
                })
            }))
        });
    }
    handleCancelDel(){
        this.setState({
            modalDel:{
                visible:false
            }
        })
    }
    deleteImage(){
        const name = this.state.image.name !== ''?this.state.image.name :'佚名',
            check = this.state.image.check_item_name;
        this.setState({
            modalDel:{
                visible:true,
                text:`您确认要删除 ${name} 的 ${check} 影像吗？`,
                title:'删除影像'
            }
        });
    }
    pass(e){
        e.preventDefault();
        const name = e.target.name;
        this.setState({
            modal:{
                visible:true,
                text:`您正在审核 ${name} 影像`,
                title:'审核影像'
            }
        });
    }
    handleOk(e){
        e.preventDefault();
        const _this = this,
            studyId = _this.props.params.id;
        _this.setState({
            modal:{
                confirmLoading: true,
                visible:true,
                text:_this.state.modal.text,
                title:_this.state.modal.title,
                type:false
            }
        },function(){
            const sendData = Object.assign({},{id:studyId,status:2},_this.props.form.getFieldsValue());
            _this.props.dispatch(updateImage(sendData,function(){
                message.success('影像通过审核',1,function(){
                    _this.setState({
                        modal: {
                            confirmLoading: false,
                            visible:false,
                            text:'',
                            title:'',
                            pid:''
                        }
                    },function(){
                        try{
                            _this.props.dispatch(fetchUserImage(studyId,function(res){
                                const image = res.content,
                                    pid = image.pid;
                                _this.props.dispatch(fetchPatient(pid,function(res){
                                    const newState = {
                                        image,
                                        patient: res.content
                                    };
                                    _this.setState({...newState})
                                }));
                            },function(){
                                message.error('影像获取失败',1,function(){
                                    _this.context.router.push('/examine')
                                })
                            }));
                        }catch(e){}

                    })
                });
            },function(res){
                message.error(`出错了！！${res.head.msg}`,1)
            }))
        });
    }
    handleReject(e){
        e.preventDefault();
        const _this = this,
            studyId = _this.props.params.id;
        _this.setState({
            modal:{
                confirmLoading: true,
                visible:true,
                text:_this.state.modal.text,
                title:_this.state.modal.title,
                type:true
            }
        },function(){
            const memo = this.props.form.getFieldsValue().memo;
            if(!!memo){
                const sendData = Object.assign({},{id:studyId,status:(-2)},_this.props.form.getFieldsValue());
                _this.props.dispatch(updateImage(sendData,function(){
                    message.success('影像通过审核',1,function(){
                        _this.setState({
                            modal: {
                                confirmLoading: false,
                                visible:false,
                                text:'',
                                title:'',
                                pid:''
                            }
                        },function(){
                            try{
                                _this.props.dispatch(fetchUserImage(studyId,function(res){
                                    const image = res.content,
                                        pid = image.pid;
                                    _this.props.dispatch(fetchPatient(pid,function(res){
                                        const newState = {
                                            image,
                                            patient: res.content
                                        };
                                        _this.setState({...newState})
                                    }));
                                }));
                            }catch(e){}
                        })
                    });
                },function(res){
                    message.error(`出错了！！${res.head.msg}`,1)
                }))
            }else{
                message.warning('审核不通过时需要填写拒绝理由',2);
                return
            }
        });
    }
    handleCancel(){
        this.setState({
            modal:{
                visible:false
            }
        })
    }
    componentWillMount(){
        const _specialists = this.props.items,
          target = _.filter(_specialists,(_s)=>{
              return _s.account_id == this.props.params.id
          })[0];
        if(!target){
            this.context.router.push('/specialist-list')
        }else{
            const account_id = this.props.params.id;
            this.props.dispatch(fetchPortrait(account_id))
        }
        this.setState({
            specialist:target,
            portrait:this.props.portrait.url
        })
    }
    toEdit(e){
        e.preventDefault();
        const _id = this.state.specialist.account_id;
        this.context.router.push(`/specialist-edit/${_id}`)
    }
    unPass(){}
    render(){
        const { getFieldProps } = this.props.form;
        const memoProps = getFieldProps('memo', {
            rules: [
                { required: this.state.modal.type, message: this.state.modal.msg }
            ]
        });
        const statusRender = function(isPass,status,context){
            const layout = {
                xs:10,
                sm:8,
                md:6,
                lg:4
            },layoutRight = {
                xs:14,
                sm:16,
                md:18,
                lg:20
            };
            switch (isPass){
                case 0:
                  //待审核
                return (
                  <Row style={{padding:'20px',background:'#eee',borderRadius:'8px'}}>
                      <Col {...layout}>
                          <h3>待审核</h3>
                      </Col>
                      <Col {...layoutRight} style={{textAlign:'right'}}>
                          <Button type="primary" size="large" onClick={context.pass.bind(context)}>
                              审核通过
                          </Button>
                          <Button type="" size="large" onClick={context.unPass.bind(context)}>
                              拒绝
                          </Button>
                      </Col>
                  </Row>
                );
                case 1:
                  //审核通过
                    return (
                      <Row style={{padding:'20px',background:'#eee',borderRadius:'8px'}}>
                          <Col {...layout}>
                              <Tag color="green">通过审核</Tag>&nbsp;&nbsp;{status == 0?<Tag color="red">已停用</Tag>:<Tag color="green">正常</Tag>}
                          </Col>
                          <Col {...layoutRight} style={{textAlign:'right'}}>
                              <Button type="primary" onClick={context.toEdit.bind(context)}>编辑</Button>
                          </Col>
                      </Row>
                    );
                case 2:
              //拒绝
                return (
                  <Row style={{padding:'20px',background:'#eee',borderRadius:'8px'}}>
                      <Col {...layout}>
                          <Tag color="">已驳回</Tag>
                      </Col>
                      <Col {...layoutRight} style={{textAlign:'right'}}>
                          {context.state.specialist.remarks}
                      </Col>
                  </Row>
                );
                default:
                return (
                  <Row style={{padding:'20px',background:'#eee',borderRadius:'8px'}}>
                      <Col {...layout}>
                          <Tag color="">测试状态</Tag>
                      </Col>
                      <Col {...layoutRight} style={{textAlign:'right'}}>
                          <Button type="primary" size="large" onClick={context.toEdit.bind(context)}>编辑</Button>
                          &nbsp;&nbsp;&nbsp;&nbsp;
                          <Button type="primary" size="large" onClick={context.pass.bind(context)}>
                              审核通过
                          </Button>
                          &nbsp;&nbsp;&nbsp;&nbsp;
                          <Button type="" size="large" onClick={context.unPass.bind(context)}>
                              拒绝
                          </Button>
                      </Col>
                  </Row>
                );
            }
        };
        const colWidth1 = {
            xs:10,
            sm:8,
            md:8,
            lg:8
        },colWidth2 = {
            xs:14,
            sm:16,
            md:16,
            lg:16
        },colWidth3 = {
            xs:{span:23,offset:1},
            sm:{span:23,offset:1},
            md:{span:11,offset:1},
            lg:{span:11,offset:1}
        };
        const _this =this;
        return (
            <div style={{ background: '', padding: '10px' }}>

                {statusRender(this.state.specialist.ispass,this.state.specialist.status,_this)}
                <Row justify="space-around" align="top">
                    <Col {...colWidth1}>
                        <img style={{
                            width:'80%',
                            margin:'0 auto'
                        }}
                             src={`${API_URL}${PORTRAIT}/${this.state.specialist.account_id}`} />
                    </Col>
                    <Col {...colWidth2}>
                        <Row justify="space-around" align="top">
                            <Col {...colWidth3}>
                                <ul className="label-list">
                                    <li><label>姓名</label>{this.state.specialist.name || `--`} </li>
                                    <li><label>性别</label>{this.state.specialist.gender || `--`} </li>
                                    <li><label>职称</label>{this.state.specialist.title || `--`} </li>
                                    <li><label>所属医院</label>{this.state.specialist.hospital || `--`} </li>
                                    <li><label>所属科室</label>{this.state.specialist.department || `--`} </li>
                                    <li><label>擅长领域</label>{this.state.specialist.domain || `--`} </li>
                                    <li><label>简历</label>{this.state.specialist.brief_introduction || `--`} </li>
                                    <li><label>阅片类型</label>{this.state.specialist.modalities || `--`} </li>
                                </ul>
                            </Col>
                            <Col {...colWidth3}>
                                <ul className="label-list">
                                    <li><label>手机号</label>{this.state.specialist.mobile || `--`} </li>
                                    <li><label>身份证号</label>{this.state.specialist.idcard || `--`} </li>
                                </ul>
                                <img style={{
                            width:'100%',
                            margin:'0 auto'
                        }}
                                     src={this.state.specialist.cardurl} />
                            </Col>
                        </Row>
                    </Col>
                </Row>

                {`${this.state.image.status}`==1?<Modal title={this.state.modal.title}
                       visible={this.state.modal.visible}
                       confirmLoading={this.state.modal.confirmLoading}
                       onCancel={this.handleCancel}
                       footer={[
                            <Button key="ok" type="primary" size="large" onClick={this.handleOk}>
                                审核通过
                            </Button>,
                            <Button key="reject" type="" size="large" onClick={this.handleReject}>
                                驳回
                            </Button>,
                            <Button key="back" type="ghost" size="large" onClick={this.handleCancel}>
                                取消
                            </Button>
                        ]}
                >
                    <p>{this.state.modal.text}</p>
                    <Form>
                        <FormItem
                            help="请注明审核结果的原因"
                        >
                            <Input
                                {...memoProps}
                                type="textarea" placeholder="请注明审核结果的原因" />
                        </FormItem>
                    </Form>
                </Modal>:''}
                <Modal title={this.state.modalDel.title}
                       visible={this.state.modalDel.visible}
                       onOk={this.handleOkDel}
                       confirmLoading={this.state.modalDel.confirmLoading}
                       onCancel={this.handleCancelDel}
                >
                    <p>{this.state.modalDel.text}</p>
                </Modal>
            </div>
        )
    }
}

_SpecialistDetail = Form.create()(_SpecialistDetail);
/**
 * @#$注意：
 * 初步加载时fetch了数据，
 * 后面还使用connect关联store中的数据，
 * 这是重复的，以后根据数据缓存策略再作调整
 * */

const SpecialistDetail = connect((state)=>{
    const {user,portrait} = state.rootReducer,
      {items} = state.rootReducer.specialist;
    return {user,items,portrait}
})(_SpecialistDetail);
export default SpecialistDetail;